﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace LuaNet
{
    class LuaHookProxy
    {
        static List<LuaHookProxy> _Proxies = new List<LuaHookProxy>();

        LuaHookProxy() 
        {
        	
        }

        public static LuaHookProxy FindProxy(LuaHook hook)
        {
            if (hook == null) return null;
            lock (_Proxies)
            return _Proxies.FirstOrDefault(p => p.ManagedHook == hook);
        }

        public static LuaHookProxy FindProxy(Lua.lua_Hook hook)
        {
            if (hook == null) return null;
            lock (_Proxies)
            return _Proxies.FirstOrDefault(p => p.UnmanagedHook == hook);
        }

        public static LuaHookProxy GetProxy(LuaHook hook)
        {
            if (hook == null) return null;
            var result = FindProxy(hook);
            if (result == null)
            {
                result = new LuaHookProxy() {
                    ManagedHook = hook
                };
                result.UnmanagedHook = result.InvokeManagedHook;
                lock (_Proxies)
                _Proxies.Add(result);
            }
            return result;
        }

        public static LuaHookProxy GetProxy(Lua.lua_Hook hook)
        {
            if (hook == null) return null;
            var result = FindProxy(hook);
            if (result == null)
            {
                result = new LuaHookProxy() {
                    UnmanagedHook = hook
                };
                result.ManagedHook = result.InvokeUnmanagedHook;
                lock (_Proxies)
                    _Proxies.Add(result);
            }
            return result;
        }

        void InvokeUnmanagedHook(LuaState state, ILuaDebug d)
        {
            LuaState ls = state as LuaState;
        }

        void InvokeManagedHook(IntPtr state, IntPtr ptr)
        {
            LuaState ls = LuaState.FindState(state, true);
            if (ManagedHook != null && ls != null)
            {
                ILuaDebug ar = new LuaDebugProxy(ptr, LuaGetInfoWhat.CurrentLine);
                ManagedHook(ls, ar);
            }
        }
        
        public LuaHook ManagedHook { get; private set; }
        public Lua.lua_Hook UnmanagedHook { get; private set; }
    }

}
